<?php

include_once "common_functions.php";
pcntl_async_signals(true);
$sigHandler=function ($signo)
{
    echo posix_getpid()." get ".$signo.PHP_EOL;
    exit(0);
};

function fork()
{
    global $childs;
    $pid = pcntl_fork();
    if ($pid < 0) die("fork err");
    if ($pid == 0) {
        $child_pid = posix_getpid();
        while (true) {
            sleep(10);
        }

    } else {
        $parent_pid = posix_getpid();
        $childs[$pid] = $pid;
    }
}

pcntl_signal(SIGINT,$sigHandler);
echo posix_getpid() . PHP_EOL;

$childs = [];
$worker_num = 3;

//daemon();


for ($i = 0; $i < $worker_num; $i++) {
    fork();
}
while (count($childs)) {
    if (($exit_id = pcntl_wait($status)) > 0) {
        $signo = pcntl_wtermsig($status);

        unset($childs[$exit_id]);
    }
    if (count($childs) < $worker_num) {
        fork();
    }
}
